package com.erp.common.web;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.erp.app.common.BBA;
import com.erp.app.common.ProjectConstants;
import com.erp.app.common.VUtil.io.UnicodeReader;
import com.erp.framework.util.CommonUtil;

public class BBAAction extends Action
{

    public ActionForward perform(ActionMapping mapping,
								 ActionForm formIn,
								 HttpServletRequest request,
								 HttpServletResponse response)
		throws ServletException
    {



		HttpSession session = request.getSession(false);
		ActionErrors errors = new ActionErrors();
    	ActionForward actionForward = new ActionForward(mapping.getInput());

    	// check if login-ed
    	if (!ProjectConstants.GENERIC_YES.equals(session.getAttribute(ProjectConstants.SESSION_BBA_LOGIN_SUCCESS))) {
    		actionForward = mapping.findForward("bbaLogin");
    		return actionForward;
    	}

		BBAForm form = (BBAForm) formIn;

		boolean isDumpInsert = "Y".equalsIgnoreCase(form.getIsDumpInsert());
		boolean isSuppressQuotes = "Y".equalsIgnoreCase(form.getIsSuppressQuotes());
		boolean isUsePre = "Y".equalsIgnoreCase(form.getIsUsePre());
		boolean isClear = "Y".equalsIgnoreCase(form.getIsClear());
		boolean isIgnoreError = "Y".equalsIgnoreCase(form.getIsIgnoreError());
		boolean isShowRealName = "Y".equalsIgnoreCase(form.getIsShowRealName());
		boolean isSingleStmt = "Y".equalsIgnoreCase(form.getIsSingleStmt());
		boolean isSaveQueryResult = null != request.getParameter("btn_save");

		String query = getQuery(form);
System.out.println("Query = " + query);

		// Action: Logout
		if ("Logout".equals(request.getParameter("btn_logout"))) {
			session.setAttribute(ProjectConstants.SESSION_BBA_LOGIN_SUCCESS, null);
			actionForward = mapping.findForward("bbaLogin");
			return actionForward;
		}

		// Action: Update
		if ("Update".equals(request.getParameter("btn_update"))) {
			if (!CommonUtil.isEmpty(query)) {
				try {
					BBA bba = getBBAFromSession(session);
					bba.setIsIgnoreError(isIgnoreError);				
					Object o = bba.invoke(query, true);

					form.setOutputHTML(showPre(o+""));
				} catch ( Exception e ) {
					form.setOutputHTML(showPre(e.getMessage()));
				}
			}
		}

		// Action: Query
		if ("Query".equals(request.getParameter("btn_query")) || isSaveQueryResult ) {
			if (!CommonUtil.isEmpty(query)) {
				try {
					BBA bba = getBBAFromSession(session);
					bba.setIsDumpInsert(isDumpInsert);
					bba.setIsSuppressQuotes(isSuppressQuotes);
					bba.setIsIgnoreError(isIgnoreError);
					bba.setIsShowRealName(isShowRealName);
					bba.setIsSingleStmt(isSingleStmt);

					Date dStart = new Date();
					Object o = bba.invoke(query, false);
					long diff = new Date().getTime() - dStart.getTime();

					if ( o instanceof Exception ) {

						form.setOutputHTML(showPre(((Exception)o).getMessage()));

					} else if ( o instanceof Object[] ) {

						StringBuffer s = new StringBuffer(1024768);
						Object rezs[] = (Object[])o;

						if ( isSaveQueryResult ) {
							OutputStream out = response.getOutputStream();
							response.setContentType("application/octet-stream");
							response.setHeader("Content-Disposition","attachment;filename=\"result.xls\"");
							response.setStatus(response.SC_OK);
							
							Object rows[] = (Object[])rezs[2];
							
							HSSFWorkbook wb = new HSSFWorkbook();
							HSSFSheet sheet = wb.createSheet();
							
							for ( int i = 0; i < rows.length; i++ ) {
								HSSFRow row = sheet.createRow(i);
								Object[] columns = (Object[])rows[i];
								for ( int j = 0; j < columns.length; j++ ) {
									HSSFCell cell = row.createCell((short)j);
									Object obj = columns[j];
									if ( obj instanceof Date ) {
										cell.setCellValue((Date)obj);
									} else if ( obj instanceof Timestamp ) {
										cell.setCellValue(new Date(((Timestamp)obj).getTime()));
									} else {
										cell.setEncoding(HSSFCell.ENCODING_COMPRESSED_UNICODE);
										cell.setCellValue(""+obj);
									}
								}
							}
							wb.write(out);
							out.close();

							actionForward = null;
						} else {
							for ( int ir = 0; ir < rezs.length; ir++ ) {
								s.append("<table cellspacing=0 cellpadding=2 class=table>");
								Object rows[] = (Object[])rezs[ir];
								boolean bFirst = true;
								for ( int i = 0; i < rows.length; i++ ) {
									Object columns[] = (Object[])rows[i];
									s.append("<tr valign=top>");
									if ( 0 == columns.length )
										bFirst = true;
									for ( int j = 0; j < columns.length; j++ ) {
										s.append("<td>" + (bFirst ? "<b>" : "") + columns[j] + (bFirst ? "</b>" : "") + "</td>");
									}
									if ( 0 != columns.length )
										bFirst = false;
									s.append("</tr>\n");
								}
								s.append("</table><br>\n");
							}
	
							form.setOutputHTML(s.toString());
						}
					} else {
System.out.println("STRING use pre? " + isUsePre);
						String s = (String)o;
						if ( isUsePre ) {
							form.setOutputHTML(showPre(s));
						}
						else
							form.setOutputHTML(CommonUtil.stringRpl(s, "\n", "<br>"));
					}
				} catch ( Exception e ) {
					form.setOutputHTML(showPre(e.getMessage()));
				}
			}
		}
		/*

		// Action: Save
		if ("Save to File".equals(request.getParameter("btn_save"))) {
			if ( form.getInputQuery() != null ) {
				byte [] bytes = form.getInputQuery().getBytes();
				if ( bytes != null ) {
					try {
						OutputStream out = response.getOutputStream();
						response.setContentType("text/html");
						response.setHeader("Content-Disposition","attachment;filename=\"query.txt\"");
						response.setStatus(response.SC_OK);
						out.write(bytes);
						out.flush();
						out.close();

						actionForward = null;
					} catch (Exception e) {
						System.err.println("Error in export: " + e.getMessage());
					}
				}
			}
		}
		*/

		try {
			int stat = 0;
			if (!CommonUtil.isEmpty(form.getStatCode())) {
				stat = Integer.parseInt(form.getStatCode());
			}
			form.setStatCode(String.valueOf(stat+1));
		} catch (Exception e){
		}

		return actionForward;
}


	public String getQuery(BBAForm form) {

		FormFile file = form.getTheFile();

		if ( file != null && !CommonUtil.isEmpty(file.getFileName()) ) {
System.out.println("uploading file .... ");
			try {
				UnicodeReader in = new UnicodeReader(file.getInputStream());
				StringWriter out = new StringWriter();
				int n = 0;
				char cbuf[] = new char[32768];
				while ( in.ready() ) {
					n = in.read(cbuf);
					out.write(cbuf, 0, n);
				}
				return out.toString();
			} catch ( IOException x ) {
				return null;
			}
		}
		else
			return form.getInputQuery();
	}

	public String showPre(String s) {
		return "<pre>" + s + "</pre>";
	}

	public BBA getBBAFromSession(HttpSession session) {
		BBA obj = null;
		try {
			if (session != null) {
				obj = (BBA) session.getAttribute(BBA.class.getName());
			}
		} catch (Exception e) {
		} finally {
			if ( obj == null ) {
				obj = new BBA();
				if (session != null ) {
					session.setAttribute(BBA.class.getName(), obj);
				}
			}
		}
 		return obj;
	}

}
